import threading
import gtyTools.gtyLog
from uiFiles.ui_wifidhcpdialog import Ui_dhcp_dialog
from PyQt5.QtWidgets import QDialog, QMessageBox
import warnings
import subprocess
from gtyConfig import language, systemConfig

warnings.filterwarnings("ignore", category=DeprecationWarning)


class myUI(QDialog):
    def __init__(self, mainPage):
        super().__init__()
        self.ui = Ui_dhcp_dialog()
        self.ui.setupUi(self)
        self.mainPage = mainPage
        self.sudo_password = systemConfig.passwd
        self.ssid = "Not connected to WiFi"
        self.initUI_connect_and_show()
        self.init_language()

    def run_sudo_command(self, command, **kwargs):
        """运行需要 sudo 权限的命令"""
        if self.sudo_password:
            # 使用 echo 密码 | sudo -S 命令格式
            command = f"echo {self.sudo_password} | sudo -S {command}"
            result = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
                                    **kwargs)
            # 检查命令是否成功执行
            if result.returncode == 0:
                return result
        return None

    def get_current_ssid(self):
        """获取当前连接的 WiFi 的 SSID"""
        try:
            # 使用 nmcli 获取当前连接的 WiFi 信息
            cmd = 'nmcli c show --active'
            result = self.run_sudo_command(cmd)
            lines = result.stdout.strip().split('\n')
            for line in lines:
                if 'wifi' in line:
                    line_lst = line.split()
                    self.ssid = ''.join(line_lst[:-3])
        except Exception as e:
            self.ui.label_disply.setText(f'get current wifi ssid failed {e}')
        self.ui.label_wifi_ssid.setText(f'{language.wifi_current_wifi}:{self.ssid}')

    # 已弃用，有线连接可重新启用用于检查激活的网络接口名称
    # def active_interfaces(self):
    #     """返回激活的网络接口"""
    #     try:
    #         # 使用ip命令列出所有网络接口及其状态
    #         result = subprocess.run(['ip', 'link'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    #         output = result.stdout.decode('utf-8')
    #         interfaces = []
    #         for line in output.split('\n'):
    #             if 'UP' in line and 'LOWER_UP' in line and 'lo' not in line: # 排除lo本地回环接口
    #                 parts = line.split(':')
    #                 if len(parts) > 1:
    #                     interfaces.append(parts[1].strip())
    #         return interfaces
    #     except Exception as e:
    #         self.ui.label_disply.setText(f'get active interfaces failed {e}')
    #         return []

    def set_dhcp(self):
        """设置DHCP"""
        self.ui.label_disply.setText('setting DHCP')
        try:
            if self.ssid == "Not connected to WiFi":
                self.ui.label_disply.setText('please connect to wifi')
                return
            commands = [
                f"nmcli connection modify id {self.ssid} ipv4.method auto",
                f" nmcli connection down id '{self.ssid}' ",
                f" nmcli connection up id {self.ssid} ifname wlan0 "
            ]
            # 将所有命令合并为一个命令字符串，用 && 连接
            combined_command = ' && '.join(commands)
            # 调用一次 sudo 命令
            result = self.run_sudo_command(combined_command)
            if result:
                gtyTools.gtyLog.log.write(__file__, f'设置DHCP成功：{self.ssid}\n')
            else:
                self.ui.label_disply.setText(f'{language.wifi_display_set_dhcp_failed}\nNone')
                return
            # 输出信息
            self.ui.label_disply.setText(language.wifi_display_set_dhcp_success)
        except Exception as e:
            self.ui.label_disply.setText(f'{language.wifi_display_set_dhcp_failed}\n{e}')

    def set_staicip(self):
        if self.ssid == "Not connected to WiFi":
            self.ui.label_disply.setText('warning:please connect to wifi')
            return
        """设置静态IP前提醒"""
        reply = QMessageBox.question(self, 'warning',
                                     f'an error setting static IP may cause network unstable, '
                                     f'do you want to continue?',
                                     QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if reply == QMessageBox.No:
            return
        self.ui.label_disply.setText('setting static IP')
        try:

            ip = self.ui.lineEdit_ip.text().split('.')
            if len(ip) != 4:
                self.ui.label_disply.setText('IP format error ')
                return
            for i in ip:
                if not i.isdigit() or int(i) < 0 or int(i) > 255:
                    self.ui.label_disply.setText('IP format error ')
                    return
            ip = self.ui.lineEdit_ip.text()

            mask_lst = self.ui.lineEdit_mask.text().split('.')
            if len(mask_lst) != 4:
                self.ui.label_disply.setText('mask format error ')
                return
            for i in mask_lst:
                if not i.isdigit() or int(i) < 0 or int(i) > 255:
                    self.ui.label_disply.setText('mask format error ')
                    return
            mask_1 = self.ui.lineEdit_mask.text()
            mask = str(sum([bin(int(i)).count('1') for i in mask_lst]))

            gateway = self.ui.lineEdit_gateway.text().split('.')
            if len(gateway) != 4:
                self.ui.label_disply.setText('gateway format error ')
                return
            for i in gateway:
                if not i.isdigit() or int(i) < 0 or int(i) > 255:
                    self.ui.label_disply.setText('gateway format error ')
                    return
            gateway = self.ui.lineEdit_gateway.text()

            dns_servers = self.ui.lineEdit_dns.text().split(',')
            for dns in dns_servers:
                if dns.strip() == "":
                    self.ui.label_disply.setText('DNS format error1：None')
                    return
                parts = dns.split('.')
                if len(parts) != 4:
                    self.ui.label_disply.setText('DNS format error2：length error')
                    return
                for part in parts:
                    if int(part) < 0 or int(part) > 255:
                        self.ui.label_disply.setText(f'DNS format error3:value error\n{parts}')
                        return
            dns = self.ui.lineEdit_dns.text()

            commands = [
                f"nmcli connection modify id '{self.ssid}' ipv4.addresses {ip}/{mask} ipv4.gateway {gateway} ipv4.dns {dns} ipv4.method manual",
                f" nmcli connection down id '{self.ssid}' ",
                f" nmcli connection up id '{self.ssid}' ifname wlan0 "
            ]
            # 将所有命令合并为一个命令字符串，用 && 连接
            combined_command = ' && '.join(commands)
            # 调用一次 sudo 命令
            result = self.run_sudo_command(combined_command)
            if result:
                gtyTools.gtyLog.log.write(__file__, f'设置静态IP成功：{ip}/{mask_1} {gateway} {dns}\n')
            else:
                self.ui.label_disply.setText(f'{language.wifi_display_set_static_ip_failed}\nNone')
                return
            # 输出信息
            self.ui.label_disply.setText(
                f'{language.wifi_display_set_static_ip_success}\nip:{ip}\nmask:{mask_1}\ngateway:{gateway}\ndns:{dns}')

        except Exception as e:
            self.ui.label_disply.setText(f'{language.wifi_display_set_static_ip_failed}\n{e}')

    def initUI_connect_and_show(self):
        self.ui.pushButton_staicIP.clicked.connect(self.set_staicip)
        self.ui.pushButton_DHCP.clicked.connect(self.set_dhcp)
        self.ui.pushButton_Quit.clicked.connect(self.close)

    def init_wifi_info(self, wifi_info_dict):
        # 检查是否有错误信息,如果有，初始化界面使用默认值
        if 'error' in wifi_info_dict:
            self.ui.lineEdit_ip.setText('192.168.1.100')
            self.ui.lineEdit_mask.setText('255.255.255.0')
            self.ui.lineEdit_gateway.setText('192.168.1.1')
            self.ui.lineEdit_dns.setText('192.168.1.1')
            return
        # 如果没有错误，使用传入的字典中的信息初始化界面
        if wifi_info_dict['ip[2]'] != '':
            self.ui.lineEdit_ip.setText(wifi_info_dict['ip[2]'])
            self.ui.lineEdit_mask.setText(wifi_info_dict.get('mask[2]', ''))
        else:
            self.ui.lineEdit_ip.setText(wifi_info_dict.get('ip[1]', ''))
            self.ui.lineEdit_mask.setText(wifi_info_dict.get('mask[1]', ''))
        self.ui.lineEdit_gateway.setText(wifi_info_dict.get('gateway', ''))
        self.ui.lineEdit_dns.setText(wifi_info_dict.get('dns', ''))

    def init_language(self):
        self.ui.label_disply.setWordWrap(True)  # 设置label的文本自动换行
        p = threading.Thread(target=self.get_current_ssid)
        p.start()  # 会阻塞的部分，放在线程里执行
        self.ui.pushButton_Quit.setText(language.wifi_exit_setting)
        self.ui.pushButton_DHCP.setText(language.wifi_set_to_dhcp)
        self.ui.pushButton_staicIP.setText(language.wifi_set_to_static_ip)
        self.ui.label_gatway.setText(language.wifi_gateway)
        self.ui.label_mask.setText(language.wifi_mask)
